<?php

namespace core\system;

use core\util\TextUtil;

class HttpRequest {

    public static function GET($name = null) {
        $get = ($name == null) ? $name : (isset($_GET[$name]) ? $_GET[$name] : null);
        if ($get == null) {
            $queryString = parse_url($_SERVER["REQUEST_URI"], PHP_URL_QUERY);
            $queryString = explode("&", $queryString);
            foreach ($queryString as $qstring) {
                $qstring = explode("=", $qstring);
                if ($qstring[0] == $name) {
                    return $qstring[1];
                }
            }
        }
        return $get;
    }

    public static function POST($name = null) {
        $post = ($name == null) ? $name : (isset($_POST[$name]) ? $_POST[$name] : null);
        if ($post == null) {
            $post = json_decode(file_get_contents("php://input"));
            $post = isset($post->$name) ? $post->$name : null;
        }
        return $post;
    }

    public static function REQUEST($name = null) {
        return ($name == null) ? $name : (isset($_REQUEST[$name]) ? $_REQUEST[$name] : null);
    }

    public static function content($type = "POST", $dataType = 'json', $class = null) {
        if ($_SERVER["REQUEST_METHOD"] != $type)
            return null;
        $data = file_get_contents("php://input");
        if ($data == null)
            return null;
        switch ($dataType) {
            case 'json':
                $data = json_decode($data);
                break;
        }
        if ($class != null) {
            $data = TextUtil::recast($class, $data);
        }
        return $data;
    }

    public static function getRequest($class) {
        $reflectionClass = new \ReflectionClass($class);
        $new = new $class;
        foreach ($reflectionClass->getProperties() as $property) {
            $property = $property->name;
            $new->$property = self::GET($property);
        }
        return $new;
    }

}
